import {Sequelize} from "sequelize";
import constant from "../common/constant.js";

const {SQL_SERVER} = constant;
const sqlServerSeq = new Sequelize(SQL_SERVER.DB_NAME, SQL_SERVER.USER, SQL_SERVER.PASSWORD, {
  host: SQL_SERVER.HOST,
  port: SQL_SERVER.PORT,
  dialect: 'mssql',
  dialectOptions: {
    options: {
      encrypt: false, // 如果你的SQL Server使用加密，请设置为true
      dateStrings: true, //将Date格式化日期字符串
    },
    charset: 'utf8mb4',
    collate: 'utf8mb4_unicode_ci',
    supportBigNumbers: true,
    bigNumberStrings: true,
    dateStrings: true, //将Date格式化日期字符串
    typeCast: true,
  },
  define: {
    // underscored: true,// 数据库启用下划线命名法,
    timestamps: false,
    freezeTableName: true,
  },
  pool: {
    max: 5,
    min: 0,
    acquire: 30000,
    idle: 10000
  },
  // logging: true,
  // timezone: '+08:00',
});
sqlServerSeq.authenticate().then(() => {
  console.log('数据库连接成功');
}).catch(err => {
  console.error('数据库连接失败', err);
});

// 原始查询的结果映射函数，将下划线字段名转换为驼峰式
function mapKeysToCamelCase(rows) {
  return rows.map(row => {
    const camelCaseRow = {};
    for (const key in row) {
      if (Object.prototype.hasOwnProperty.call(row, key)) {
        // 将下划线字段名转换为驼峰式
        const camelCaseKey = key.replace(/_([a-z])/g, (match, letter) => letter.toUpperCase());
        camelCaseRow[camelCaseKey] = row[key];
      }
    }
    return camelCaseRow;
  });
}

// 在查询之前设置字段名转换规则
sqlServerSeq.addHook('beforeFind', (options) => {
  if (options.type === 'SELECT') {
    options.fieldMap = options.fieldMap || {};
    options.fieldMap = Object.keys(options.model.rawAttributes).reduce((fieldMap, fieldName) => {
      const field = options.model.rawAttributes[fieldName];
      fieldMap[field.fieldName] = field.fieldName;
      fieldMap[field.fieldName] = field.fieldName.replace(/_(\w)/g, (all, letter) => letter.toUpperCase());
      return fieldMap;
    }, {});
  }
});
export {sqlServerSeq, mapKeysToCamelCase};

// module.exports = mapKeysToCamelCase;